package com.gy.wx_demo_mg.service;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.gy.wx_demo_mg.dao.ManagerUserDao;
import com.gy.wx_demo_mg.entity.ManagerUser;
import com.gy.wx_demo_mg.service.serviceinterface.BaseService;
import com.gy.wx_demo_mg.service.serviceinterface.ManagerUserService;
import com.gy.wx_demo_mg.utils.RSon;

/**
 * @author GY
 * 2017年12月28日
 */
@Service("baseService")
public class BaseServiceImp implements BaseService {
    private static Logger logger = LoggerFactory.getLogger(BaseServiceImp.class);
    
    @Autowired
    private ManagerUserDao managerUserDao;
    @Autowired
    private ManagerUserService managerUserService;

    @Override
    public void regist(ManagerUser user,RSon rson) {
        Integer userId;
        try {
            userId = managerUserDao.findManagerUserIdByUserName(user.getUserName());
        } catch (Exception e) {
            logger.error("数据库查询用户异常:"+e.getMessage(),e);
            RSon.error(rson, RSon.DAO_ERROR_CODE);
            return;
        }
        if(userId != null){
            //用户名已经存在不可注册
            RSon.error(rson, RSon.USER_NAME_EXIST_ERROR);
            return;
        }
        //新增管理员用户数据
        managerUserService.addManagerUser(user,rson);
        user.setPassword("");//密码置空
        rson.setData(user);
    }
    
    @Override
    public void login(String userName, String password, RSon rson) {
        String realPassword = managerUserDao.selectPasswordByUserName(userName);
        if(StringUtils.isEmpty(realPassword)){
            //用户不存在
            RSon.error(rson, RSon.USER_ERROR_CODE);
            return;
        }
        //校验登录密码
        boolean result = checkPassword(password,realPassword);
        if(!result){
            //密码错误
            RSon.error(rson, RSon.USER_PASSWORD_ERROR);
            return;
        }
    }
    
    /**
     * @param password
     * @param realPassword
     * @return
     * GY
     * 2017年12月29日
     * 校验密码
     */
    private boolean checkPassword(String password, String realPassword){
        if(!password.equals(realPassword)){
            return Boolean.FALSE;
        }
        return Boolean.TRUE;
    }
    
    @Override
    public boolean checkCode(HttpServletRequest request, String code) {
        String codeKey = (String)request.getSession().getAttribute(CODE_KEY);
        if(!StringUtils.isEmpty(codeKey)){
            request.getSession().removeAttribute(CODE_KEY);
        }
        if(StringUtils.isEmpty(codeKey)|| (!codeKey.equals(code))){
            return Boolean.FALSE;
        }
        return Boolean.TRUE;
    }

}
